package models

import (
	"gorm.io/gorm"
)

type Book struct {
	gorm.Model
	Title   string `gorm:"type:varchar(20);comment:'图书名称'"`
	TypesId int64  `gorm:"type:int;comment:'类型 1-文学类、2-科技类、3-教育类、4-工具类'"`
	Num     int64  `gorm:"type:int;comment:'库存 不能小于1'"`
	Status  int64  `gorm:"type:int;default:0;comment:'图书状态 1-在馆、2-已借出、3-已下架'"`
}

func (b *Book) CreateBook(db *gorm.DB) error {
	return db.Create(&b).Error
}

func (b *Book) BookList(db *gorm.DB, page, pageSize int,
	title string, typesId, status int64) (list []Book, err error) {

	query := db.Debug()

	if title != "" {
		query = query.Where("title like ?", "%"+title+"%")
	}
	if typesId != 0 {
		query = query.Where("types_id = ?", typesId)
	}
	if status != 0 {
		query = query.Where("status = ?", status)
	}

	err = query.
		Scopes(Paginate(page, pageSize)).
		Find(&list).Error

	return list, err
}

func (b *Book) GetBookById(db *gorm.DB, id int64) error {
	return db.Where("id=?", id).Limit(1).Find(&b).Error
}

func (b *Book) UpdateStatus(db *gorm.DB, status int64) error {
	return db.Model(&b).Update("status", status).Error
}

func (b *Book) DelBook(db *gorm.DB) error {
	return db.Delete(&b).Error
}

func Paginate(page, pageSize int) func(db *gorm.DB) *gorm.DB {
	return func(db *gorm.DB) *gorm.DB {
		if page <= 0 {
			page = 1
		}

		switch {
		case pageSize > 100:
			pageSize = 100
		case pageSize <= 0:
			pageSize = 10
		}

		offset := (page - 1) * pageSize
		return db.Offset(offset).Limit(pageSize)
	}
}

type User struct {
	gorm.Model
	Account  string `gorm:"type:varchar(20);comment:'账号'"`
	Password string `gorm:"type:varchar(20);comment:'密码'"`
	Status   int64  `gorm:"type:int;comment:'用户权限状态 1-管理员 2-读者'"`
}

func (u *User) GetUserByAccount(db *gorm.DB, account string) error {
	return db.Where("account=?", account).Limit(1).Find(&u).Error
}
